#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from bottle import Bottle
from bottle import request, response

from comm.beans.SysDictObj import SysDictObj
from conn.MyRedisFactory import RedisConfig

HealthyCMVAdm = Bottle()

@HealthyCMVAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@HealthyCMVAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class WeightLossPlanRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    pru_tuut_db_conn = None
    weightLossPlanServiceImpl = None
    _dict = None

    def __init__(self, pru_tuut_db_conn, weightLossPlanService, rds_cfg):
        WeightLossPlanRoute.pru_tuut_db_conn = pru_tuut_db_conn
        WeightLossPlanRoute._dict = SysDictObj(pru_tuut_db_conn)
        WeightLossPlanRoute.rds_cfg = rds_cfg
        WeightLossPlanRoute.weightLossPlanServiceImpl = weightLossPlanService
        return

    @staticmethod
    @HealthyCMVAdm.get('/calFoodCatalogs')
    def cal_food_catalogs():
        calorie = request.params.calories
        protein = request.params.proteinWeight
        fat = request.params.fatWeight
        carbonWater = request.params.carbonWaterWeight
        vitamin = request.params.vitaminWeight
        count = 1
        _catalogs = []
        # 数据库中读取数据的分类，并生成计算公式用的配比
        _groups = WeightLossPlanRoute.weightLossPlanServiceImpl.calculation_ingredient_groups()
        if _groups['code'] == 200:
            for i in _groups['data']:
                if i[1] == "protein":
                    _catalogs.append({"key": i[0], "val": protein})
                if i[1] == "fat":
                    _catalogs.append({"key": i[0], "val": fat})
                if i[1] == "carbonWater":
                    _catalogs.append({"key": i[0], "val": carbonWater})
                if i[1] == "vitamin":
                    _catalogs.append({"key": i[0], "val": vitamin})
        res = WeightLossPlanRoute.weightLossPlanServiceImpl.calculation_ingredient_ratio(calorie=calorie,
                                                                    count=count,
                                                                    catalogs=_catalogs)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': WeightLossPlanRoute.ERROR_CODE["99"]}
        view_list = res['data']
        return {'code': 200, 'data': view_list, 'message': ""}

    @staticmethod
    @HealthyCMVAdm.post('/calPairings')
    def cal_pairings():
        import datetime
        dinnertimes = {"zaocan": "早餐", "wucan": "午餐", "wancan": "晚餐"}  # 早中晚3餐食
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        view_list = []
        if request.json is not None:
            params = request.json['params']
            memberId = request.json['memberId']
            _str_mem_json = RedisConfig.get_val(WeightLossPlanRoute.rds_cfg, key=f'hcm:mem:{memberId}_info', json_flg=True)
            _obj_mem = json.loads(_str_mem_json)
            # 更换第二版计算方案。放弃原定食材用量及配餐方式 3月27日需求调整
            # view_list = WeightLossPlanRoute.weightLossPlanServiceImpl.calculation_dinner(params, dinnertimes)['data']
            _choose_cust_dinner_switch = WeightLossPlanRoute._dict.load_dict_val(key_eng="custDinnerSw")["data"]["val"]
            if str(_choose_cust_dinner_switch).upper() == 'ON':
                # 使用固定菜谱
                _str_static_dinner = WeightLossPlanRoute._dict.load_dict_val(key_eng="custDinner")["data"]["val"]
                _arry_static_dinner = json.loads(_str_static_dinner)
                _arry_dashabi_days = []
                for day in _arry_static_dinner:
                    _arry_dashabi_cans = []
                    for one_can in day["can"]:
                        _arry_dashabi_foods = dashabi(one_can["foods"], params)
                        # 计算维生素食材的克重数量，从计算餐食数量，转换到整餐食数量空，依据餐食标准值，超过餐食则表现实际值，否则依据标准餐食-热量餐食 / 维生素餐食数量 核准计算。 4月8日调整
                        cal_col_intake_weight = [i["intake"] for i in _arry_dashabi_foods]
                        cal_col_intake_tot_weight = sum(cal_col_intake_weight)
                        if int(_obj_mem["sex"]) == 0:
                            dinner_std_weight = WeightLossPlanRoute._dict.load_dict_val(key_eng="mDinnerStdKgs")["data"]["val"]
                        elif int(_obj_mem["sex"]) == 1:
                            dinner_std_weight = WeightLossPlanRoute._dict.load_dict_val(key_eng="fDinnerStdKgs")["data"]["val"]
                        # 计算补差的维生素配菜
                        if float(dinner_std_weight) > cal_col_intake_tot_weight:
                            diff_weight = float(dinner_std_weight) - cal_col_intake_tot_weight
                        elif float(dinner_std_weight) < cal_col_intake_tot_weight:
                            # 补充一定比值的维生素配餐
                            _str_VitaminProportion = WeightLossPlanRoute._dict.load_dict_val(key_eng="VitaminProportion")["data"][
                                "val"]
                            diff_weight = float(dinner_std_weight) * (float(_str_VitaminProportion) / 100)
                        # 获取配餐维生素餐食
                        arry_vim_foods = [i for i in _arry_dashabi_foods if i["classification"] == "维生素"]
                        for vim_foods in arry_vim_foods:
                            vim_foods["intake"] = round(diff_weight / len(arry_vim_foods), 0)
                        _arry_dashabi_cans.append({"name": dinnertimes[one_can["name"]], "foods": _arry_dashabi_foods})
                    _arry_dashabi_days.append(_arry_dashabi_cans)
            else:
                # 使用随机菜谱,与固定餐谱不一样，这里没有循环天数，仅在食谱库中，对应类别数据进行一次随机计算
                carbonWater_count = WeightLossPlanRoute._dict.load_dict_val(key_eng="carbonWaterCount")["data"]["val"]
                carbonWater_dinners = WeightLossPlanRoute._dict.load_dict_val(key_eng="carbonWater")["data"]["val"]
                fat_count = WeightLossPlanRoute._dict.load_dict_val(key_eng="fatCount")["data"]["val"]
                fat_dinners = WeightLossPlanRoute._dict.load_dict_val(key_eng="fat")["data"]["val"]
                vitamin_count = WeightLossPlanRoute._dict.load_dict_val(key_eng="vitaminCount")["data"]["val"]
                vitamin_dinners = WeightLossPlanRoute._dict.load_dict_val(key_eng="vitamin")["data"]["val"]
                protein_count = WeightLossPlanRoute._dict.load_dict_val(key_eng="proteinCount")["data"]["val"]
                protein_dinners = WeightLossPlanRoute._dict.load_dict_val(key_eng="protein")["data"]["val"]
                _arry_dashabi_cans = []
                for key, val in dinnertimes.items():
                    _arry_dashabi_foods = []
                    random_choose_food_data(carbonWater_count, carbonWater_dinners, _arry_dashabi_foods)
                    random_choose_food_data(fat_count, fat_dinners, _arry_dashabi_foods)
                    random_choose_food_data(vitamin_count, vitamin_dinners, _arry_dashabi_foods)
                    random_choose_food_data(protein_count, protein_dinners, _arry_dashabi_foods)
                    _arry_dashabi_foods = dashabi(_arry_dashabi_foods, params)
                    _arry_dashabi_cans.append({"name": val, "foods": _arry_dashabi_foods})
                _arry_dashabi_days = [_arry_dashabi_cans]
            view_list = _arry_dashabi_days
            _obj = {"list": view_list, "desp": "数据仅供参考", "currentDate": now}
            return {'code': 200, 'data': _obj, 'message': ""}


def random_choose_food_data(cal_foods_count, cal_foods, arry_foods):
    import random
    lst = json.loads(cal_foods)
    for cols in range(int(cal_foods_count)):
        random_element = random.choice(lst)
        arry_foods.append(random_element)
    return arry_foods


def dashabi(arryA, ArryB):
    res = []
    for food_cal in arryA:
        _tmp = [j for j in ArryB if j["classification"] == food_cal["catalog"]][0]
        for key, val in _tmp.items():
            food_cal[key] = val
        food_cal["cal_intake"] = food_cal["intake"]
        # -------------------------------------------------------------------------------------------------------------
        # 加入数据库内食材克重转化的计算，参考 WeightLossPlanService 31行
        check_cal_flg_data = WeightLossPlanRoute.weightLossPlanServiceImpl.load_one_food({"name": food_cal["key"]})
        recal = True
        if check_cal_flg_data is not None and check_cal_flg_data[5] == "1":
            recal = False
        items = WeightLossPlanRoute.weightLossPlanServiceImpl.load_food_data(
            {"name": food_cal["key"], "catalog": food_cal["catalog"], "single_food_weight": food_cal["intake"]},
            recal=recal)
        if len(items) > 0:
            if items[0][1] == "鱼油":
                if items[0][5] >0 and items[0][5] < 1:
                    food_cal["intake"] = 1
                else:
                    food_cal["intake"] = 1+round(items[0][5], 0)
            food_cal["unit_content_index"] = round(float(check_cal_flg_data[5]), 0)
        else:
            food_cal["intake"] = 0
            food_cal["unit_content_index"] = 0
        res.append(food_cal)
    return res
